<template>
  <div class="app-container">
    <!-- 宇宙背景 -->
    <div class="universe-bg"></div>
    <div class="stars" id="stars"></div>

    <!-- 顶部导航 -->
    <el-header class="header">
      <div class="logo">灵次元</div>
      <el-input
        v-if="currindex === '2'"
        v-model="searchQuery"
        placeholder="搜索作品、创作者或标签..."
        prefix-icon="el-icon-search"
        class="search-bar"
      />
      <!-- 复用 RuoYi 用户组件：登录状态判断 -->
      <div class="user-container">
        <!-- 未登录：显示登录按钮 -->
        <el-button v-if="!isLoggedIn" type="primary" @click="showLoginModal = true" class="login-btn">登录</el-button>
        <!-- 已登录：复用 RuoYi 下拉菜单 -->
        <el-dropdown v-else class="avatar-container hover-effect" trigger="hover" popper-append-to-body>
          <div class="avatar-wrapper">
            <img :src="avatar" class="user-avatar" />
            <span class="user-nickname">{{ nickName }}</span>
          </div>
          <el-dropdown-menu slot="dropdown">
            <router-link to="/userInfo">
              <el-dropdown-item>个人中心</el-dropdown-item>
            </router-link>
            <el-dropdown-item divided @click.native="logout">
              <span>退出登录</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 侧边导航 -->
    <el-aside class="side-nav">
      <div v-if="!isLoggedIn" class="navshi" @click.stop="getkdle"></div>
      <el-menu :default-active="currindex" class="nav-menu" :router="false">
        <el-menu-item index="1" @click="currindex = '1'">
          <div class="menu-icon">🎨</div>
          <div class="menu-text">创作</div>
        </el-menu-item>
        <el-menu-item index="2" @click="currindex = '2'" class="active">
          <div class="menu-icon">🔍</div>
          <div class="menu-text">探索</div>
        </el-menu-item>
        <el-menu-item index="3" @click="changeTab('3')">
          <div class="menu-icon">🎪</div>
          <div class="menu-text">活动</div>
        </el-menu-item>
        <el-menu-item index="4" @click="changeTab('4')">
          <div class="menu-icon">💬</div>
          <div class="menu-text">消息</div>
        </el-menu-item>
        <el-menu-item index="5" @click="changeTab('5')">
          <div class="menu-icon">👤</div>
          <div class="menu-text">我的</div>
        </el-menu-item>
        <el-menu-item index="6" @click="changeTab('6')">
          <div class="menu-icon">ℹ️</div>
          <div class="menu-text">关于</div>
        </el-menu-item>
        <el-menu-item index="7" @click="changeTab('7')">
          <div class="menu-icon">⚙️</div>
          <div class="menu-text">设置</div>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主内容区 -->
    <el-container>
      <!-- 探索页标签 -->
      <div class="explore-tabs" v-if="currindex === '2'">
        <el-tabs v-model="activeExploreTab" :before-leave="handleBeforeLeave" @tab-click="handleTabChange">
          <el-tab-pane label="推荐" name="recommend" />
          <el-tab-pane label="收藏" name="favorites" />
          <el-tab-pane label="关注" name="follow" />
        </el-tabs>
      </div>
      <work-item v-if="currindex === '2'" class="content_box" :activeTab="activeExploreTab" />
      <div v-if="currindex === '3'" class="contentactive">
        <ActivityList />
      </div>
    </el-container>

    <!-- 加载提示 -->
    <!-- <el-dialog :visible.sync="loading" title="" :show-close="false" class="loading-overlay">
      <div style="text-align: center">正在加载...</div>
    </el-dialog> -->
    <div v-if="showLoginModal" class="login-modal">
      <LingCiyuanLogin @close="handleModalClose" @login-success="handleLoginSuccess" />
    </div>
  </div>
</template>
<script>
import WorkItem from './components/worklist.vue'
import ActivityList from './components/active.vue'
import LingCiyuanLogin from './components/loginForm.vue'
import { Message } from 'element-ui'
import QRCode from 'qrcode'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { sendYzm, welogin, login } from '@/api/workserve'
import '@/assets/wxLogin.js'
import store from '@/store'
import { mapGetters } from 'vuex'
// 导入 RuoYi 所需组件（根据你的项目路径调整）
// import Hamburger from '@/components/Hamburger' // 若不需要可删除
// import TopNav from '@/components/TopNav' // 若不需要可删除
export default {
  components: {
    WorkItem,
    LingCiyuanLogin,
    ActivityList,
  },
  data() {
    return {
      // 状态管理
      searchQuery: '',
      showLoginModal: false,
      activeLoginTab: 'wechat',
      phoneNumber: '',
      password: '',
      activeExploreTab: 'recommend',
      scanMaskVisible: false, // 新增：扫码后遮罩是否显示
      loading: false,
      currindex: '2',
      showCommentPanel: false,
      comments: [],
      status: '',
      handFlag: false,
      codeUrl: '',
      state: '',
      pollTimer: null,
      smsCode: '', // 新增：验证码
      countdown: 60, // 倒计时初始值
      canSendSms: true, // 是否可发送验证码
      newComment: '',
      commentCount: 0,
      workItems: [],
      appid: '',
      redirect_uri: '',
    }
  },
  mounted() {
    // 主页面挂载时，检查URL是否包含微信回调的code参数
    if (window.location.search.includes('code=')) {
      this.handleCallback()
    }
  },
  computed: {
    ...mapGetters(['nickName', 'avatar']),
    // 判断是否已登录（根据 RuoYi 的 token 状态）
    isLoggedIn() {
      return !!getToken() // 复用 auth.js 中的 getToken 方法
    },
  },
  methods: {
    handleModalClose() {
      this.showLoginModal = false
    },
    getkdle() {
      // 1. 未登录：提示并重置激活状态，阻止后续操作
      if (!getToken()) {
        this.$message.warning('请先登录再操作！') // 改用 warning 提示更醒目
        return
      }
    },
    handleLoginSuccess() {
      this.showLoginModal = false
      // 接收子组件传递的用户信息，做后续处理（如存缓存、跳转页面）
      location.reload()
    },
    changeTab(index) {
      // 2. 已登录：执行对应菜单的跳转逻辑（根据索引区分）
      switch (index) {
        case '1':
          // 创作页面路由跳转
          this.$router.push('/create')
          break
        case '2':
          // 探索页面（当前默认页面，可留空或刷新数据）
          break
        case '3':
          this.currindex = '3'
          break
        case '4':
          this.$router.push('/messages')
          break
        case '5':
          this.$router.push('/userCenter')
          break
        case '6':
          this.$router.push('/about')
          break
        case '7':
          this.$router.push('/settings')
          break
      }
    },

    getQueryString(name) {
      const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`)
      const r = window.location.search.substr(1).match(reg)
      if (r != null) return decodeURIComponent(r[2])
      return null
    },
    // 处理微信回调
    async handleCallback() {
      try {
        // 1. 从URL中获取微信返回的code和state
        const code = this.getQueryString('code')
        // 校验参数是否存在
        if (!code) {
          return
        }
        // 3. 调用后端接口，通过code获取登录凭证
        const res = await welogin({ code })
        setToken(res.data.token)
        this.$store.commit('SET_USER_INFO', res.data.profile)
        Message.success('登录成功')
        location.reload()
      } catch (err) {
        this.loading = false
        this.error = err.message || '登录失败，请重试'
        console.error('微信登录回调失败：', err)
      }
    },
    handleBeforeLeave() {
      if (!this.isLoggedIn) {
        this.$message.warning('请登录后再操作哦！')
        // this.showLoginModal = true
        return false // 阻止切换
      }
      return true // 允许切换
    },
    handleTabChange() {
      // 切换标签时加载对应数据
      // this.loading = true
      // setTimeout(() => {
      //   this.loading = false
      // }, 500)
    },
    logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        background: 'rgba(0, 0, 0, 0.7)',
      })
        .then(() => {
          this.$store.commit('user/SET_USER_INFO')
          // localStorage.removeItem('nickName')
          // localStorage.removeItem('avatar')
          // localStorage.removeItem('userinfo')
          // removeToken()
          location.reload()
        })
        .catch(() => {})
    },
    sendComment() {
      if (!this.newComment.trim()) {
        Message.warning('请输入评论内容')
        return
      }
      // 添加新评论
      this.comments.push({
        id: Date.now(),
        author: '当前用户',
        time: new Date().toLocaleString(),
        avatar: '', // 可以设置用户头像
        content: this.newComment,
      })
      this.commentCount = this.comments.length
      this.newComment = ''
      Message.success('评论成功')
    },
  },
}
</script>

<style lang="scss" scoped>
@import './index.css';
.user-container {
  display: flex;
  align-items: center;
  .avatar-container {
    color: #fff;
    .avatar-wrapper {
      display: flex;
      align-items: center;
      cursor: pointer;
      .user-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        margin-right: 8px;
        border: 2px solid rgba(255, 255, 255, 0.3);
      }
      .user-nickname {
        font-size: 14px;
        white-space: nowrap;
      }
    }
    // 下拉菜单样式适配
    ::v-deep .el-dropdown-menu {
      background: rgba(26, 31, 46, 0.95);
      border: 1px solid rgba(255, 255, 255, 0.1);
      .el-dropdown-item {
        color: #fff;
        &:hover {
          background: rgba(110, 69, 226, 0.3);
        }
      }
    }
  }
  .login-btn {
    // 原有登录按钮样式保留，可微调适配
    background: linear-gradient(45deg, #6e45e2, #88d3ce);
    border: none;
    border-radius: 20px;
    padding: 8px 20px;
  }
}
.contentactive {
  width: 80%;
  // height: 100vh;
  // background: rgba(26, 31, 46, 0.95);
  margin: auto;
}
// 适配退出登录弹窗样式
::v-deep .el-dialog__body {
  color: #fff;
}
::v-deep .el-confirm-dialog__footer {
  .el-button {
    &.el-button--primary {
      background: linear-gradient(45deg, #6e45e2, #88d3ce);
      border: none;
    }
    &.el-button--default {
      background: transparent;
      color: #fff;
      border: 1px solid rgba(255, 255, 255, 0.3);
    }
  }
}
.login-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 500;
  background: rgba(0, 0, 0, 0.7);
  justify-content: center;
  align-items: center;
  .modalbox {
    background: #1a1f2e;
    border-radius: 20px;
    padding: 30px;
    padding-top: 10px;
    width: 400px;
    max-width: 90%;
    min-height: 360px;
    padding-top: 30px;
    color: #fff;
    position: relative;
    top: 200px;
    // margin-height: -200px;
    left: 50%;
    margin-left: -200px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
    .qrcode-container {
      text-align: center;
    }
    .box_cencl {
      position: absolute;
      right: 15px;
      top: 10px;
      font-size: 20px;
      cursor: pointer;
    }
    .box_txt {
      font-size: 24px;
      margin-bottom: 10px;
      text-align: center;
    }
    .codeul {
      width: 150px;
      height: 150px;
      margin: auto;
    }
    .scan-mask {
      position: absolute;
      top: 0;
      left: 50%;
      margin-left: -75px;
      width: 150px;
      height: 150px;
      background: rgba(0, 0, 0, 0.9);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 10;
      color: white;
      font-size: 18px;
      .scan-mask-content {
        text-align: center;
        i {
          font-size: 32px;
          margin-bottom: 10px;
          display: block;
          animation: rotate 1s linear infinite;
        }
      }
    }
    .login-form {
      margin-bottom: 20px;
      text-align: center;
    }
    .login-input {
      margin: 10px 0;
    }
    .login-submit {
      width: 100%;
      padding: 12px;
      background: linear-gradient(45deg, #6e45e2, #88d3ce);
      border: none;
      border-radius: 20px;
      color: white;
      font-weight: bold;
      cursor: pointer;
      margin-top: 10px;
    }
    ::v-deep .el-tabs__active-bar {
      display: inline-block;
      margin-left: 15px;
      // background-color: transparent !important;
      width: 40px !important;
    }
    ::v-deep .el-tabs__nav-wrap::after {
      height: 0 !important;
      position: static !important;
    }
    ::v-deep .el-input__inner {
      background: rgba(255, 255, 255, 0.2);
      color: #fff !important;
      border: none;
      box-shadow: none;
    }
    .login-link {
      font-size: 12px;
      margin-top: 5px;
    }
    .sms-code-row {
      display: flex;
      gap: 10px;
      margin: 10px 0;
    }

    .sms-input {
      flex: 1;
    }

    .sms-btn {
      width: auto;
      height: 36px;
      margin-top: 10px;
      text-align: center;
      border-radius: 20px;
      background: linear-gradient(45deg, #6e45e2, #88d3ce);
      border: none;
      color: white;
    }
    .sms-btn:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
  }
}
.content_box {
  margin-top: 150px;
  margin-left: -100px;
  position: absolute;
  left: -50px;
}
::v-deep .header .el-input__inner {
  background: rgba(255, 255, 255, 0);
  color: #fff !important;
  border: none;
  box-shadow: none;
}
::v-deep .el-menu {
  background: rgba(255, 255, 255, 0);
}
.explore-tabs ::v-deep .el-tabs__active-bar {
  display: inline-block;
  margin-left: 5px;
  // background-color: transparent !important;
  width: 20px !important;
}
.login-modal ::v-deep .el-tabs__active-bar {
  // margin-left: 18px;
}
.explore-tabs ::v-deep .el-tabs__nav-wrap::after {
  height: 0 !important;
  position: static !important;
}
::v-deep .el-tabs__item {
  font-size: 16px;
  color: #fff;
  // padding-bottom: 20px;
  border-bottom: none !important;
}
::v-deep .el-tabs__header {
  border-bottom: none !important;
}
::v-deep .explore-tabs .el-tabs__item.is-active {
  color: #0066cc !important;
  font-weight: bold;
}
::v-deep .el-aside {
  width: 80px !important; // 清除 300px 固定宽度
  // padding: 0 16px; // 可选：添加内边距，避免内容贴边
}
::v-deep .el-dialog__wrapper {
  background-color: rgba(10, 5, 25, 0.7) !important; // 深色半透明，适配宇宙主题
}
.side-nav {
  // position: relative;
  .navshi {
    position: absolute;
    left: 0;
    top: 0;
    width: 300px;
    height: 600px;
    cursor: pointer;
    background: rgba(255, 255, 255, 0);
    z-index: 8000;
  }
}
</style>
